<template>
  <el-card>
    <el-form inline class="category-selector-form">
      <el-form-item label="一级分类">
        <!-- 
          必须绑定v-model收集数据，才能选中值
         -->
        <el-select v-model="category1Id">
          <!-- 
            label 显示的内容
            value 选中的值
              因为将来获取二级分类，需要一级分类id
           -->
          <el-option
            v-for="c1 in category1List"
            :key="c1.id"
            :label="c1.name"
            :value="c1.id"
          />
        </el-select>
      </el-form-item>

      <el-form-item label="二级分类">
        <el-select v-model="category2Id">
          <el-option
            v-for="c2 in category2List"
            :key="c2.id"
            :label="c2.name"
            :value="c2.id"
          />
        </el-select>
      </el-form-item>

      <el-form-item label="三级分类">
        <el-select v-model="category3Id">
          <el-option
            v-for="c3 in category3List"
            :key="c3.id"
            :label="c3.name"
            :value="c3.id"
          />
        </el-select>
      </el-form-item>
    </el-form>
  </el-card>
</template>

<script lang="ts">
export default {
  name: "CategorySelector",
};
</script>

<script lang="ts" setup>
/*
  1. 一上来请求一级分类列表
  2. 选择一级分类，请求二级分类列表
  3. 选择二级分类，请求三级分类列表
*/
import { ref, onMounted, watch } from "vue";
import {
  getCategory1ListApi,
  getCategory2ListApi,
  getCategory3ListApi,
} from "@/api/product/category";
import type { CategoryList } from "@/api/product/model/categoryModel";

const category1List = ref<CategoryList>([]);
const category2List = ref<CategoryList>([]);
const category3List = ref<CategoryList>([]);

const category1Id = ref<undefined | number>();
const category2Id = ref<undefined | number>();
const category3Id = ref<undefined | number>();

// 1. 一上来请求一级分类列表
onMounted(async () => {
  category1List.value = await getCategory1ListApi();
});

watch(category1Id, async (newVal) => {
  // 选择一级分类(当一级分类id发生变化)，请求二级分类列表
  category2List.value = await getCategory2ListApi(newVal as number);
  // 清空二级和三级分类id
  category2Id.value = undefined;
  category3Id.value = undefined;
  // 清空三级分类列表
  category3List.value = [];
});

watch(category2Id, async (newVal) => {
  if (!newVal) return;
  // 选择二级分类，请求三级分类列表
  category3List.value = await getCategory3ListApi(newVal as number);
  category3Id.value = undefined;
});
</script>

<style scoped>
.category-selector-form :deep(.el-form-item) {
  margin-top: 10px;
  margin-bottom: 10px;
}
</style>
